package javabase.collection.list.performance;

import java.util.ArrayList;
import java.util.List;

public final class EnsureCapacityDemo {
	private static final int INITIAL_NO = 10000000;
	public static void main(String[] args) {
		Object obj = new Object();
		List<Object> list = new ArrayList<Object>();
//		ArrayList<Object> list = new ArrayList<Object>();
		long st = System.nanoTime();
		for (int i = 0; i < INITIAL_NO; i++) {
			list.add(obj);
		}
		System.out.println("没有ensureCapacity方法：" + (System.nanoTime() - st));
		list.clear();
		System.out.println("clear之后的数量" + list.size());
		list = null;
		
	/*		
	 * 当可以预估数组比较大时
	 * 	1.new ArrayList<Object>(INITIAL_NO)
		2.list = new ArrayList<Object>(INITIAL_NO);
		  ((ArrayList<Object>)list).ensureCapacity(INITIAL_NO);*/
		
		list = new ArrayList<Object>(INITIAL_NO);
		((ArrayList<Object>)list).ensureCapacity(INITIAL_NO);
		
		st = System.nanoTime(); // 31899655
		for (int i = 0; i < INITIAL_NO; i++) {
			list.add(obj);
		}
		System.out.println("使用ensureCapacity方法：" + (System.nanoTime() - st));
		
	}

}
